package com.haiwen.boot.service.lmpl;
import com.haiwen.boot.mapper.BlogMapper;

import com.haiwen.boot.pojo.BlogWithBLOBs;
import com.haiwen.boot.service.BlogContentService;
import com.haiwen.boot.utils.DateStringMutual;
import com.haiwen.boot.utils.RedisContext;
import com.haiwen.boot.utils.RedisUtil;
import com.haiwen.boot.vo.ResultMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class BlogContentImpl implements BlogContentService {
    @Autowired
    private BlogMapper mapper;
    @Autowired
    private ResultMap resultMap;
    @Autowired
   private RedisUtil redisUtil;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public int TextUpload(BlogWithBLOBs record) {
        String regEx="[\n`~!@#$%^&*()+=|{}]"; //正则表达，去除文本中的特殊字符
        String nullStr = " ";
        int TempTotalWords = record.getBlContent().replaceAll(regEx, nullStr).length();
        String totalWords=TempTotalWords+"";
        String readingTime=(int)Math.ceil(TempTotalWords*1.0/500)+"";
        String blContent = record.getBlContent().endsWith("\n")?record.getBlContent():record.getBlContent()+"\n";
        int firstNum= blContent.indexOf('#');
        int TitleNum = blContent.indexOf("\n",firstNum);
        int length = blContent.length();
        String Title;
        String Content=blContent.substring(TitleNum);
        Date date=new Date();
        String time = DateStringMutual.DateToStringUtil(date);
        if (firstNum==-1){
            if (length<10){
                Title = blContent.substring(0, length);
            }else {
                Title=blContent.substring(0,10);
            }
        }else {
            Title = blContent.substring(firstNum,TitleNum).replaceAll("#","").trim();
        }
        record.setTitle(Title);
        record.setBlContent(Content);
        BlogWithBLOBs blogWithBLOBs = mapper.selectByTitle(Title);
        if (blogWithBLOBs!=null){
            record.setModifyTime(time);
            record.setTotalWords(totalWords);
            record.setReadingTime(readingTime);
            //执行更新操作
            return mapper.updateByPrimaryKeySelective(record);
        }
        record.setReleaseTime(time);
        record.setModifyTime(time);
        record.setTotalWords(totalWords);
        record.setReadingTime(readingTime);
        return mapper.insertSelective(record);
    }
    @Override
    public List<BlogWithBLOBs> listShow(Boolean isdel) {
        return mapper.listShow(isdel);
    }

    @Override
    public ResultMap delAndRelByTitle(BlogWithBLOBs record){
        int nums = mapper.updateByPrimaryKeySelective(record);
        if (record.getIsdel()!=null){
            if (nums>=1){
                return resultMap.code(200).message("删除成功").success();
            }
             return resultMap.code(500).message("删除失败").fail();
        }
        if (nums>=1){
            return resultMap.code(200).message("发布成功").success();
        }
        return resultMap.code(500).message("发布失败").fail();
    }

    @Override
    public BlogWithBLOBs blogShow(Integer blId) {
        return mapper.selectByPrimaryKey(blId);
    }

    @Override
    public void Reading(Integer blId) {
        //记录浏览量到redis,然后定时更新到数据库
        String key= RedisContext.ARTICLE_VIEWCOUNT_CODE+blId;
            redisUtil.set(key,blId,100);
            //找到redis中该篇文章的浏览数，如果不存在则向redis中添加一条
            Map<Object,Object> viewCountItem=redisUtil.hmget(RedisContext.ARTICLE_VIEWCOUNT_KEY);
            Integer viewCount=0;
            if(!viewCountItem.isEmpty()){
                if(viewCountItem.containsKey(key)){
                    viewCount=(Integer)viewCountItem.get(key);
                    redisUtil.hset(RedisContext.ARTICLE_VIEWCOUNT_KEY,key,viewCount+1);
                }else {
                    redisUtil.hset(RedisContext.ARTICLE_VIEWCOUNT_KEY,key,1);
                }
            }else{
                redisUtil.hset(RedisContext.ARTICLE_VIEWCOUNT_KEY,key,1);
            }
        }
    //定时写入数据库
    @Override
    @Scheduled(cron = "0 0/1 * * * ?")//每1分钟
    public void WriteDataReading() {
            logger.info("开始保存点赞数 、浏览数");
            try {
                //先获取这段时间的浏览数
                Map<Object,Object> viewCountItem=redisUtil.hmget(RedisContext.ARTICLE_VIEWCOUNT_KEY);
                //然后删除redis里这段时间的浏览数
                redisUtil.remove(RedisContext.ARTICLE_VIEWCOUNT_KEY);
                if(!viewCountItem.isEmpty()){
                    for(Object item :viewCountItem.keySet()){
                        String articleKey=item.toString();
                        String[]  kv=articleKey.split("_");
                        int articleId=Integer.parseInt(kv[1]);
                        String viewCount= viewCountItem.get(articleKey)+"";
                        System.out.println("文章id:"+articleId+"浏览量:"+viewCount);
                        mapper.Reading(viewCount,articleId);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
            logger.info("结束保存点赞数 、浏览数");
    }
}
